<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="searchParam" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="标签">
          <n-input v-model:value="searchParam.key" placeholder="请输入关键字查询" clearable/>
        </n-form-item>
        <n-form-item label="类型">
          <n-select v-model:value="searchParam.type" :options="typeOptions" style="width: 110px;" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="searchParam.status" :options="statusOptions" style="width: 110px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(searchParam.key=null,searchParam.status=null,searchParam.type=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list" :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="searchParam"
                list-url="tags/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['tags:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!--  新增、修改数据  -->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改标签':'新增标签'" :mask-closable="false"
             :show-icon="false" preset="dialog" @after-leave="closeAddEditModel">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-width="auto" label-placement="left">
        <n-form-item label="标签" path="name">
          <n-input v-model:value="addEditForm.name" placeholder="请填写标签" clearable/>
        </n-form-item>
        <n-form-item label="所属类型" path="type">
          <n-select v-model:value="addEditForm.type" :options="typeOptions" placeholder="请选择标签类型" clearable/>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="0" :unchecked-value="1">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </n-switch>
        </n-form-item>
        <n-form-item label="排序" path="sort" :show-feedback="false">
          <n-input-number v-model:value="addEditForm.sort" :show-button="false" placeholder="排序" clearable/>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script setup lang="ts">
import {h, ref, reactive} from 'vue'
import SearchButtonGroup from '@components/SearchButtonGroup';
import {NTag, SelectOption, NPopconfirm, useMessage, FormInst} from "naive-ui";
import DataTable from '@components/DataTable'
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {delRequest, postPutRequest} from '@/api/data.ts'
import {AddSharp} from "@vicons/material";

const message = useMessage()

const searchParam = ref({
  key: null,
  status: null,
  type: null,
})

const typeOptions = ref<SelectOption[]>([
  {
    label: '教师',
    value: 0,
  }, {
    label: '用户',
    value: 1,
  }
])
const statusOptions = ref<SelectOption[]>([
  {
    label: '启用',
    value: 0,
  }, {
    label: '停用',
    value: 1,
  }
])
//列表
const data_list = ref<any>();
const columns = ref([
  {
    title: '标签',
    key: 'name',
    width: 220,
  },
  {
    title: '类型',
    key: 'type',
    width: 100,
    render(row: { type: boolean | number }) {
      const typeText: SelectOption | undefined = typeOptions.value.find(item => item.value === row.type);
      return h('span', null,
          {
            default: () => (typeText && typeText.label),
          }
      );

    }
  }, {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center',
    render(row: { status: boolean | number }) {
      const status_color = row.status==0 ? 'success' : 'warning';
      const statusText: SelectOption | undefined = statusOptions.value.find(item => item.value === row.status);
      return h(NTag,
          {
            type: status_color,
          },
          {
            default: () => (statusText && statusText.label),
          }
      );

    }
  }, {
    title: '排序',
    key: 'sort',
    width: 100,
  }, {
    title: '创建时间',
    key: 'createTime',
    maxWidth: 175,
  }
]);
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['tags:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前标签吗？',
          },
          permission: ['tags:del']
        },
      ]
    });
  },
});
//新增、修改标签
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  name: '',
  type: null,
  status: 0,
  sort: 100,
})
const addEditFormRules = ref({
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写标签'
  },
  type: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择类型'
  }
})
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.name = record.name;
  addEditForm.value.type = record.type;
  addEditForm.value.status = record.status;
  addEditForm.value.sort = record.sort;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('tags/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//关闭新增、修改模态框
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.name = '';
  addEditForm.value.type = null;
  addEditForm.value.status = 0;
  addEditForm.value.sort = 100;
  handelSubmitLoading.value = false;
}
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'tags/edit' : 'tags/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">

</style>